package com.fang.dao;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.fang.entity.Cart;
import com.fang.utils.JDBCUtils;

public class CartDao {

	public Cart query(Cart cart) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from cart where uid=? and gid=?";
		try {
			return qr.query(sql, new BeanHandler<Cart>(Cart.class), cart.getUid(),cart.getGid());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("...");
		}
		
	}

	public void addcart(Cart cart) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "insert into cart values(?,?,?)";
		try {
			qr.update(sql,cart.getUid(),cart.getGid(),cart.getBuynum());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("...");
		}
		
	}

	public void updatecart(Cart cart) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "update cart set buynum=? where uid=? and gid=?";
		try {
			qr.update(sql, cart.getBuynum(),cart.getUid(),cart.getGid());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("...");
		}
		
		
	}

	public List<Cart> querybyuid(int uid) {
		
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from cart where uid=? ";
		try {
			return qr.query(sql, new BeanListHandler<Cart>(Cart.class), uid);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("查询购物车商品"+e);
		}
	}

	public void delete(Cart cart) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "delete from cart where gid=? and uid=?";
		try {
			qr.update(sql, cart.getGid(),cart.getUid());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("...");
		}
		
		
	}

	public void clear(Integer uid) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "delete from cart where  uid=?";
		try {
			qr.update(sql,uid);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("清除失败"+e);
		}
		
		
	}

}
